//
//  OAuthViewController.swift
//  新浪微博
//
//  Created by seteny on 16/7/10.
//  Copyright © 2016年 seteny. All rights reserved.
//

import UIKit

import SVProgressHUD
import AFNetworking

//  微博appKey
let WeiboAppKey = "1746048720"
//  微博appsecret
let WeiboAPPSecret = "2b47e284e648b6a60ccc13185aee084c"
//  微博授权回调页
let WeiboRedirect_Uri = "http://www.itcast.cn"

class OAuthViewController: UIViewController {

    // MARK:   --懒加载控件
    private lazy var weibView: UIWebView = UIWebView()
    
    override func loadView() {
        
        //自定义视图
       weibView.delegate = self
        
        //默认不透明,改成透明
        weibView.opaque = false
        
        view = weibView
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNavUI()
        
        requestOAuthLogin()
        
    }
    
    
   private func requestOAuthLogin() {
        
        //请求地址
        let url = "https://api.weibo.com/oauth2/authorize?client_id=\(WeiboAppKey)&redirect_uri=\(WeiboRedirect_Uri)"
        //准备请求对象
        let request = NSURLRequest(URL: NSURL(string: url)!)
        //加载请求
        weibView.loadRequest(request)
    }
    
    private func setupNavUI() {
        
        navigationItem.title = "微博登录"
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "取消", target: self, action: "cancelAction")
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动填充", target: self, action: "autoFillAction")
    }
    
    // MARK:  --点击事件
       @objc private func cancelAction() {
        SVProgressHUD.dismiss()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    //自动填充
    @objc private func autoFillAction() {
        
        weibView.stringByEvaluatingJavaScriptFromString("document.getElementById('userId').value = 'seteny@sina.com'; document.getElementById('passwd').value = '13872297546'")
    }
    
    
//    
//    //通过授权码(code)获取accesstoken
//    private func requesAccesstoken(code: String) {
//        
//        //准备接口地址
//        let url = "https://api.weibo.com/oauth2/access_token"
//        //准备参数
//        let params = [
//            
//            "client_id": WeiboAppKey,
//            "client_secret": WeiboAPPSecret,
//            "grant_type": "authorization_code",
//            "code": code,
//            "redirect_uri": WeiboRedirect_Uri
//        ]
//        
//        let sessioManager = AFHTTPSessionManager()
//        sessioManager.responseSerializer.acceptableContentTypes?.insert("text/plain")
//        
//        //发送post
//        sessioManager.POST(url, parameters: params, progress: nil, success: { (_, response) -> Void in
//            
//            }) { (_, error) -> Void in
//                
//        }
//    }
//    
//
//    
//    
}

//通过 UIWebViewDelegate 获取code
extension OAuthViewController: UIWebViewDelegate {
    
    //将要加载请求
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        guard let url = request.URL else {
            return false
        }
        
        //代码执行到此行,我们的url 一定有值
        //获取url的绝对地址
        if !url.absoluteString.hasPrefix(WeiboRedirect_Uri) {
            return true
        }
        
        // 代码执行到此就是我们需要关心的url字符串
        if let query = url.query where query.hasPrefix("code=") {
            
            //截取code
            let code = query.substringFromIndex("code=".endIndex)
            
           UserAccountViewModel.shareUserAccount.requestAccesstoken(code, callBack: { (isSuccess) -> () in
            
            if isSuccess {
                print("登陆成功1")
                self.dismissViewControllerAnimated(false, completion: { () -> Void in
                    
                    //  发送通知,释放资源
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootVCNotification, object: self)
                    
                })
            } else {
                print("登陆失败")
            }
           })
            
        } else {
            //进入取消回调页`
            dismissViewControllerAnimated(true, completion: nil)
        }
        
        return false
        
    }

    
    //开始加载
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    //加载完成
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    //加载失败
    func webView(webView: UIWebView, didFailLoadWithError error: NSError?) {
        SVProgressHUD.dismiss()
    }
    
    
    
    
    
    
    
    
    
}
